package com.bole.springboot_webflux.controller;

import com.bole.springboot_webflux.model.AttachmentModel;
import lombok.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * 模拟客户端请求
 */
@RequestMapping("/client")
@Controller
public class ClientController {

    @ResponseBody
    @RequestMapping("/testWebFlux/{id}")
    public Mono<AttachmentModel> testWebFlux(@PathVariable("id") String id){
        WebClient client = WebClient.create("http://127.0.0.1:8888");

        Mono<AttachmentModel> result = client.get()
                .uri("/annotated/getAttachment/{id}", id).accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(AttachmentModel.class);
        System.out.println(22222);
        result.subscribe(System.out::println);
        return result;
    }


    @ResponseBody
    @RequestMapping("/testWebFlux2/{id}")
    public Mono<AttachmentModel> testWebFlux2(@PathVariable("id") String id){
        WebClient client = WebClient.create("http://127.0.0.1:8888/annotated/getAttachmentBody");
        AttachmentModel model = new AttachmentModel();
        model.setId(id);
        Mono<AttachmentModel> mono = Mono.just(model);
        Mono<AttachmentModel> attachmentModelMono = client.post().contentType(MediaType.APPLICATION_JSON).body(mono, AttachmentModel.class).retrieve().bodyToMono(AttachmentModel.class);
        attachmentModelMono.subscribe(System.out::println);
        return attachmentModelMono;
    }

    @ResponseBody
    @RequestMapping("/testWebFlux3/{id}")
    public Mono<AttachmentModel> testWebFlux3(@PathVariable("id") String id){
        WebClient client = WebClient.create("http://127.0.0.1:8888/annotated/getAttachmentBody");
        AttachmentModel model = new AttachmentModel();
        model.setId(id);
        Mono<AttachmentModel> mono = Mono.just(model);
        Mono<AttachmentModel> attachmentModel = client.post().contentType(MediaType.APPLICATION_JSON).body(mono, AttachmentModel.class).exchange().flatMap(res -> {
            if (res.statusCode().is2xxSuccessful()) {
                return res.bodyToMono(AttachmentModel.class);
            } else {
                return Mono.error(new RuntimeException("请求失败" + res.statusCode()));
            }
        });
        attachmentModel.subscribe(System.out::println);
        return attachmentModel;
    }


}
